|
1
|
|
|
/** |
|
2
|
|
|
* @license AngularJS v1.5.0 |
|
3
|
|
|
* (c) 2010-2016 Google, Inc. http://angularjs.org |
|
4
|
|
|
* License: MIT |
|
5
|
|
|
*/ |
|
6
|
|
|
(function(window, angular, undefined) {'use strict'; |
|
7
|
|
|
|
|
8
|
|
|
var $resourceMinErr = angular.$$minErr('$resource'); |
|
9
|
|
|
|
|
10
|
|
|
// Helper functions and regex to lookup a dotted path on an object |
|
11
|
|
|
// stopping at undefined/null. The path must be composed of ASCII |
|
12
|
|
|
// identifiers (just like $parse) |
|
13
|
|
|
var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/; |
|
14
|
|
|
|
|
15
|
|
|
function isValidDottedPath(path) { |
|
16
|
|
|
return (path != null && path !== '' && path !== 'hasOwnProperty' && |
|
17
|
|
|
MEMBER_NAME_REGEX.test('.' + path)); |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
function lookupDottedPath(obj, path) { |
|
21
|
|
|
if (!isValidDottedPath(path)) { |
|
22
|
|
|
throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path); |
|
23
|
|
|
} |
|
24
|
|
|
var keys = path.split('.'); |
|
25
|
|
|
for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) { |
|
26
|
|
|
var key = keys[i]; |
|
27
|
|
|
obj = (obj !== null) ? obj[key] : undefined; |
|
28
|
|
|
} |
|
29
|
|
|
return obj; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Create a shallow copy of an object and clear other fields from the destination |
|
34
|
|
|
*/ |
|
35
|
|
|
function shallowClearAndCopy(src, dst) { |
|
36
|
|
|
dst = dst || {}; |
|
37
|
|
|
|
|
38
|
|
|
angular.forEach(dst, function(value, key) { |
|
39
|
|
|
delete dst[key]; |
|
40
|
|
|
}); |
|
41
|
|
|
|
|
42
|
|
|
for (var key in src) { |
|
43
|
|
|
if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { |
|
44
|
|
|
dst[key] = src[key]; |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return dst; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @ngdoc module |
|
53
|
|
|
* @name ngResource |
|
54
|
|
|
* @description |
|
55
|
|
|
* |
|
56
|
|
|
* # ngResource |
|
57
|
|
|
* |
|
58
|
|
|
* The `ngResource` module provides interaction support with RESTful services |
|
59
|
|
|
* via the $resource service. |
|
60
|
|
|
* |
|
61
|
|
|
* |
|
62
|
|
|
* <div doc-module-components="ngResource"></div> |
|
63
|
|
|
* |
|
64
|
|
|
* See {@link ngResource.$resource `$resource`} for usage. |
|
65
|
|
|
*/ |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* @ngdoc service |
|
69
|
|
|
* @name $resource |
|
70
|
|
|
* @requires $http |
|
71
|
|
|
* @requires ng.$log |
|
72
|
|
|
* @requires $q |
|
73
|
|
|
* @requires ng.$timeout |
|
74
|
|
|
* |
|
75
|
|
|
* @description |
|
76
|
|
|
* A factory which creates a resource object that lets you interact with |
|
77
|
|
|
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources. |
|
78
|
|
|
* |
|
79
|
|
|
* The returned resource object has action methods which provide high-level behaviors without |
|
80
|
|
|
* the need to interact with the low level {@link ng.$http $http} service. |
|
81
|
|
|
* |
|
82
|
|
|
* Requires the {@link ngResource `ngResource`} module to be installed. |
|
83
|
|
|
* |
|
84
|
|
|
* By default, trailing slashes will be stripped from the calculated URLs, |
|
85
|
|
|
* which can pose problems with server backends that do not expect that |
|
86
|
|
|
* behavior. This can be disabled by configuring the `$resourceProvider` like |
|
87
|
|
|
* this: |
|
88
|
|
|
* |
|
89
|
|
|
* ```js |
|
90
|
|
|
app.config(['$resourceProvider', function($resourceProvider) { |
|
91
|
|
|
// Don't strip trailing slashes from calculated URLs |
|
92
|
|
|
$resourceProvider.defaults.stripTrailingSlashes = false; |
|
93
|
|
|
}]); |
|
94
|
|
|
* ``` |
|
95
|
|
|
* |
|
96
|
|
|
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in |
|
97
|
|
|
* `/user/:username`. If you are using a URL with a port number (e.g. |
|
98
|
|
|
* `http://example.com:8080/api`), it will be respected. |
|
99
|
|
|
* |
|
100
|
|
|
* If you are using a url with a suffix, just add the suffix, like this: |
|
101
|
|
|
* `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')` |
|
102
|
|
|
* or even `$resource('http://example.com/resource/:resource_id.:format')` |
|
103
|
|
|
* If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be |
|
104
|
|
|
* collapsed down to a single `.`. If you need this sequence to appear and not collapse then you |
|
105
|
|
|
* can escape it with `/\.`. |
|
106
|
|
|
* |
|
107
|
|
|
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in |
|
108
|
|
|
* `actions` methods. If a parameter value is a function, it will be executed every time |
|
109
|
|
|
* when a param value needs to be obtained for a request (unless the param was overridden). |
|
110
|
|
|
* |
|
111
|
|
|
* Each key value in the parameter object is first bound to url template if present and then any |
|
112
|
|
|
* excess keys are appended to the url search query after the `?`. |
|
113
|
|
|
* |
|
114
|
|
|
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in |
|
115
|
|
|
* URL `/path/greet?salutation=Hello`. |
|
116
|
|
|
* |
|
117
|
|
|
* If the parameter value is prefixed with `@` then the value for that parameter will be extracted |
|
118
|
|
|
* from the corresponding property on the `data` object (provided when calling an action method). |
|
119
|
|
|
* For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of |
|
120
|
|
|
* `someParam` will be `data.someProp`. |
|
121
|
|
|
* |
|
122
|
|
|
* @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend |
|
123
|
|
|
* the default set of resource actions. The declaration should be created in the format of {@link |
|
124
|
|
|
* ng.$http#usage $http.config}: |
|
125
|
|
|
* |
|
126
|
|
|
* {action1: {method:?, params:?, isArray:?, headers:?, ...}, |
|
127
|
|
|
* action2: {method:?, params:?, isArray:?, headers:?, ...}, |
|
128
|
|
|
* ...} |
|
129
|
|
|
* |
|
130
|
|
|
* Where: |
|
131
|
|
|
* |
|
132
|
|
|
* - **`action`** – {string} – The name of action. This name becomes the name of the method on |
|
133
|
|
|
* your resource object. |
|
134
|
|
|
* - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`, |
|
135
|
|
|
* `DELETE`, `JSONP`, etc). |
|
136
|
|
|
* - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of |
|
137
|
|
|
* the parameter value is a function, it will be executed every time when a param value needs to |
|
138
|
|
|
* be obtained for a request (unless the param was overridden). |
|
139
|
|
|
* - **`url`** – {string} – action specific `url` override. The url templating is supported just |
|
140
|
|
|
* like for the resource-level urls. |
|
141
|
|
|
* - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, |
|
142
|
|
|
* see `returns` section. |
|
143
|
|
|
* - **`transformRequest`** – |
|
144
|
|
|
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – |
|
145
|
|
|
* transform function or an array of such functions. The transform function takes the http |
|
146
|
|
|
* request body and headers and returns its transformed (typically serialized) version. |
|
147
|
|
|
* By default, transformRequest will contain one function that checks if the request data is |
|
148
|
|
|
* an object and serializes to using `angular.toJson`. To prevent this behavior, set |
|
149
|
|
|
* `transformRequest` to an empty array: `transformRequest: []` |
|
150
|
|
|
* - **`transformResponse`** – |
|
151
|
|
|
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – |
|
152
|
|
|
* transform function or an array of such functions. The transform function takes the http |
|
153
|
|
|
* response body and headers and returns its transformed (typically deserialized) version. |
|
154
|
|
|
* By default, transformResponse will contain one function that checks if the response looks |
|
155
|
|
|
* like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, |
|
156
|
|
|
* set `transformResponse` to an empty array: `transformResponse: []` |
|
157
|
|
|
* - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the |
|
158
|
|
|
* GET request, otherwise if a cache instance built with |
|
159
|
|
|
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for |
|
160
|
|
|
* caching. |
|
161
|
|
|
* - **`timeout`** – `{number}` – timeout in milliseconds.<br /> |
|
162
|
|
|
* **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are |
|
163
|
|
|
* **not** supported in $resource, because the same value would be used for multiple requests. |
|
164
|
|
|
* If you are looking for a way to cancel requests, you should use the `cancellable` option. |
|
165
|
|
|
* - **`cancellable`** – `{boolean}` – if set to true, the request made by a "non-instance" call |
|
166
|
|
|
* will be cancelled (if not already completed) by calling `$cancelRequest()` on the call's |
|
167
|
|
|
* return value. Calling `$cancelRequest()` for a non-cancellable or an already |
|
168
|
|
|
* completed/cancelled request will have no effect.<br /> |
|
169
|
|
|
* - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the |
|
170
|
|
|
* XHR object. See |
|
171
|
|
|
* [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) |
|
172
|
|
|
* for more information. |
|
173
|
|
|
* - **`responseType`** - `{string}` - see |
|
174
|
|
|
* [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). |
|
175
|
|
|
* - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - |
|
176
|
|
|
* `response` and `responseError`. Both `response` and `responseError` interceptors get called |
|
177
|
|
|
* with `http response` object. See {@link ng.$http $http interceptors}. |
|
178
|
|
|
* |
|
179
|
|
|
* @param {Object} options Hash with custom settings that should extend the |
|
180
|
|
|
* default `$resourceProvider` behavior. The supported options are: |
|
181
|
|
|
* |
|
182
|
|
|
* - **`stripTrailingSlashes`** – {boolean} – If true then the trailing |
|
183
|
|
|
* slashes from any calculated URL will be stripped. (Defaults to true.) |
|
184
|
|
|
* - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be |
|
185
|
|
|
* cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value. |
|
186
|
|
|
* This can be overwritten per action. (Defaults to false.) |
|
187
|
|
|
* |
|
188
|
|
|
* @returns {Object} A resource "class" object with methods for the default set of resource actions |
|
189
|
|
|
* optionally extended with custom `actions`. The default set contains these actions: |
|
190
|
|
|
* ```js |
|
191
|
|
|
* { 'get': {method:'GET'}, |
|
192
|
|
|
* 'save': {method:'POST'}, |
|
193
|
|
|
* 'query': {method:'GET', isArray:true}, |
|
194
|
|
|
* 'remove': {method:'DELETE'}, |
|
195
|
|
|
* 'delete': {method:'DELETE'} }; |
|
196
|
|
|
* ``` |
|
197
|
|
|
* |
|
198
|
|
|
* Calling these methods invoke an {@link ng.$http} with the specified http method, |
|
199
|
|
|
* destination and parameters. When the data is returned from the server then the object is an |
|
200
|
|
|
* instance of the resource class. The actions `save`, `remove` and `delete` are available on it |
|
201
|
|
|
* as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, |
|
202
|
|
|
* read, update, delete) on server-side data like this: |
|
203
|
|
|
* ```js |
|
204
|
|
|
* var User = $resource('/user/:userId', {userId:'@id'}); |
|
205
|
|
|
* var user = User.get({userId:123}, function() { |
|
206
|
|
|
* user.abc = true; |
|
207
|
|
|
* user.$save(); |
|
208
|
|
|
* }); |
|
209
|
|
|
* ``` |
|
210
|
|
|
* |
|
211
|
|
|
* It is important to realize that invoking a $resource object method immediately returns an |
|
212
|
|
|
* empty reference (object or array depending on `isArray`). Once the data is returned from the |
|
213
|
|
|
* server the existing reference is populated with the actual data. This is a useful trick since |
|
214
|
|
|
* usually the resource is assigned to a model which is then rendered by the view. Having an empty |
|
215
|
|
|
* object results in no rendering, once the data arrives from the server then the object is |
|
216
|
|
|
* populated with the data and the view automatically re-renders itself showing the new data. This |
|
217
|
|
|
* means that in most cases one never has to write a callback function for the action methods. |
|
218
|
|
|
* |
|
219
|
|
|
* The action methods on the class object or instance object can be invoked with the following |
|
220
|
|
|
* parameters: |
|
221
|
|
|
* |
|
222
|
|
|
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` |
|
223
|
|
|
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` |
|
224
|
|
|
* - non-GET instance actions: `instance.$action([parameters], [success], [error])` |
|
225
|
|
|
* |
|
226
|
|
|
* |
|
227
|
|
|
* Success callback is called with (value, responseHeaders) arguments, where the value is |
|
228
|
|
|
* the populated resource instance or collection object. The error callback is called |
|
229
|
|
|
* with (httpResponse) argument. |
|
230
|
|
|
* |
|
231
|
|
|
* Class actions return empty instance (with additional properties below). |
|
232
|
|
|
* Instance actions return promise of the action. |
|
233
|
|
|
* |
|
234
|
|
|
* The Resource instances and collections have these additional properties: |
|
235
|
|
|
* |
|
236
|
|
|
* - `$promise`: the {@link ng.$q promise} of the original server interaction that created this |
|
237
|
|
|
* instance or collection. |
|
238
|
|
|
* |
|
239
|
|
|
* On success, the promise is resolved with the same resource instance or collection object, |
|
240
|
|
|
* updated with data from server. This makes it easy to use in |
|
241
|
|
|
* {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view |
|
242
|
|
|
* rendering until the resource(s) are loaded. |
|
243
|
|
|
* |
|
244
|
|
|
* On failure, the promise is rejected with the {@link ng.$http http response} object, without |
|
245
|
|
|
* the `resource` property. |
|
246
|
|
|
* |
|
247
|
|
|
* If an interceptor object was provided, the promise will instead be resolved with the value |
|
248
|
|
|
* returned by the interceptor. |
|
249
|
|
|
* |
|
250
|
|
|
* - `$resolved`: `true` after first server interaction is completed (either with success or |
|
251
|
|
|
* rejection), `false` before that. Knowing if the Resource has been resolved is useful in |
|
252
|
|
|
* data-binding. |
|
253
|
|
|
* |
|
254
|
|
|
* The Resource instances and collections have these additional methods: |
|
255
|
|
|
* |
|
256
|
|
|
* - `$cancelRequest`: If there is a cancellable, pending request related to the instance or |
|
257
|
|
|
* collection, calling this method will abort the request. |
|
258
|
|
|
* |
|
259
|
|
|
* @example |
|
260
|
|
|
* |
|
261
|
|
|
* # Credit card resource |
|
262
|
|
|
* |
|
263
|
|
|
* ```js |
|
264
|
|
|
// Define CreditCard class |
|
265
|
|
|
var CreditCard = $resource('/user/:userId/card/:cardId', |
|
266
|
|
|
{userId:123, cardId:'@id'}, { |
|
267
|
|
|
charge: {method:'POST', params:{charge:true}} |
|
268
|
|
|
}); |
|
269
|
|
|
|
|
270
|
|
|
// We can retrieve a collection from the server |
|
271
|
|
|
var cards = CreditCard.query(function() { |
|
272
|
|
|
// GET: /user/123/card |
|
273
|
|
|
// server returns: [ {id:456, number:'1234', name:'Smith'} ]; |
|
274
|
|
|
|
|
275
|
|
|
var card = cards[0]; |
|
276
|
|
|
// each item is an instance of CreditCard |
|
277
|
|
|
expect(card instanceof CreditCard).toEqual(true); |
|
278
|
|
|
card.name = "J. Smith"; |
|
279
|
|
|
// non GET methods are mapped onto the instances |
|
280
|
|
|
card.$save(); |
|
281
|
|
|
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} |
|
282
|
|
|
// server returns: {id:456, number:'1234', name: 'J. Smith'}; |
|
283
|
|
|
|
|
284
|
|
|
// our custom method is mapped as well. |
|
285
|
|
|
card.$charge({amount:9.99}); |
|
286
|
|
|
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} |
|
287
|
|
|
}); |
|
288
|
|
|
|
|
289
|
|
|
// we can create an instance as well |
|
290
|
|
|
var newCard = new CreditCard({number:'0123'}); |
|
291
|
|
|
newCard.name = "Mike Smith"; |
|
292
|
|
|
newCard.$save(); |
|
293
|
|
|
// POST: /user/123/card {number:'0123', name:'Mike Smith'} |
|
294
|
|
|
// server returns: {id:789, number:'0123', name: 'Mike Smith'}; |
|
295
|
|
|
expect(newCard.id).toEqual(789); |
|
296
|
|
|
* ``` |
|
297
|
|
|
* |
|
298
|
|
|
* The object returned from this function execution is a resource "class" which has "static" method |
|
299
|
|
|
* for each action in the definition. |
|
300
|
|
|
* |
|
301
|
|
|
* Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and |
|
302
|
|
|
* `headers`. |
|
303
|
|
|
* |
|
304
|
|
|
* @example |
|
305
|
|
|
* |
|
306
|
|
|
* # User resource |
|
307
|
|
|
* |
|
308
|
|
|
* When the data is returned from the server then the object is an instance of the resource type and |
|
309
|
|
|
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD |
|
310
|
|
|
* operations (create, read, update, delete) on server-side data. |
|
311
|
|
|
|
|
312
|
|
|
```js |
|
313
|
|
|
var User = $resource('/user/:userId', {userId:'@id'}); |
|
314
|
|
|
User.get({userId:123}, function(user) { |
|
315
|
|
|
user.abc = true; |
|
316
|
|
|
user.$save(); |
|
317
|
|
|
}); |
|
318
|
|
|
``` |
|
319
|
|
|
* |
|
320
|
|
|
* It's worth noting that the success callback for `get`, `query` and other methods gets passed |
|
321
|
|
|
* in the response that came from the server as well as $http header getter function, so one |
|
322
|
|
|
* could rewrite the above example and get access to http headers as: |
|
323
|
|
|
* |
|
324
|
|
|
```js |
|
325
|
|
|
var User = $resource('/user/:userId', {userId:'@id'}); |
|
326
|
|
|
User.get({userId:123}, function(user, getResponseHeaders){ |
|
327
|
|
|
user.abc = true; |
|
328
|
|
|
user.$save(function(user, putResponseHeaders) { |
|
329
|
|
|
//user => saved user object |
|
330
|
|
|
//putResponseHeaders => $http header getter |
|
331
|
|
|
}); |
|
332
|
|
|
}); |
|
333
|
|
|
``` |
|
334
|
|
|
* |
|
335
|
|
|
* You can also access the raw `$http` promise via the `$promise` property on the object returned |
|
336
|
|
|
* |
|
337
|
|
|
``` |
|
338
|
|
|
var User = $resource('/user/:userId', {userId:'@id'}); |
|
339
|
|
|
User.get({userId:123}) |
|
340
|
|
|
.$promise.then(function(user) { |
|
341
|
|
|
$scope.user = user; |
|
342
|
|
|
}); |
|
343
|
|
|
``` |
|
344
|
|
|
* |
|
345
|
|
|
* @example |
|
346
|
|
|
* |
|
347
|
|
|
* # Creating a custom 'PUT' request |
|
348
|
|
|
* |
|
349
|
|
|
* In this example we create a custom method on our resource to make a PUT request |
|
350
|
|
|
* ```js |
|
351
|
|
|
* var app = angular.module('app', ['ngResource', 'ngRoute']); |
|
352
|
|
|
* |
|
353
|
|
|
* // Some APIs expect a PUT request in the format URL/object/ID |
|
354
|
|
|
* // Here we are creating an 'update' method |
|
355
|
|
|
* app.factory('Notes', ['$resource', function($resource) { |
|
356
|
|
|
* return $resource('/notes/:id', null, |
|
357
|
|
|
* { |
|
358
|
|
|
* 'update': { method:'PUT' } |
|
359
|
|
|
* }); |
|
360
|
|
|
* }]); |
|
361
|
|
|
* |
|
362
|
|
|
* // In our controller we get the ID from the URL using ngRoute and $routeParams |
|
363
|
|
|
* // We pass in $routeParams and our Notes factory along with $scope |
|
364
|
|
|
* app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', |
|
365
|
|
|
function($scope, $routeParams, Notes) { |
|
366
|
|
|
* // First get a note object from the factory |
|
367
|
|
|
* var note = Notes.get({ id:$routeParams.id }); |
|
368
|
|
|
* $id = note.id; |
|
369
|
|
|
* |
|
370
|
|
|
* // Now call update passing in the ID first then the object you are updating |
|
371
|
|
|
* Notes.update({ id:$id }, note); |
|
372
|
|
|
* |
|
373
|
|
|
* // This will PUT /notes/ID with the note object in the request payload |
|
374
|
|
|
* }]); |
|
375
|
|
|
* ``` |
|
376
|
|
|
* |
|
377
|
|
|
* @example |
|
378
|
|
|
* |
|
379
|
|
|
* # Cancelling requests |
|
380
|
|
|
* |
|
381
|
|
|
* If an action's configuration specifies that it is cancellable, you can cancel the request related |
|
382
|
|
|
* to an instance or collection (as long as it is a result of a "non-instance" call): |
|
383
|
|
|
* |
|
384
|
|
|
```js |
|
385
|
|
|
// ...defining the `Hotel` resource... |
|
386
|
|
|
var Hotel = $resource('/api/hotel/:id', {id: '@id'}, { |
|
387
|
|
|
// Let's make the `query()` method cancellable |
|
388
|
|
|
query: {method: 'get', isArray: true, cancellable: true} |
|
389
|
|
|
}); |
|
390
|
|
|
|
|
391
|
|
|
// ...somewhere in the PlanVacationController... |
|
392
|
|
|
... |
|
393
|
|
|
this.onDestinationChanged = function onDestinationChanged(destination) { |
|
394
|
|
|
// We don't care about any pending request for hotels |
|
395
|
|
|
// in a different destination any more |
|
396
|
|
|
this.availableHotels.$cancelRequest(); |
|
397
|
|
|
|
|
398
|
|
|
// Let's query for hotels in '<destination>' |
|
399
|
|
|
// (calls: /api/hotel?location=<destination>) |
|
400
|
|
|
this.availableHotels = Hotel.query({location: destination}); |
|
401
|
|
|
}; |
|
402
|
|
|
``` |
|
403
|
|
|
* |
|
404
|
|
|
*/ |
|
405
|
|
|
angular.module('ngResource', ['ng']). |
|
406
|
|
|
provider('$resource', function() { |
|
407
|
|
|
var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/; |
|
408
|
|
|
var provider = this; |
|
409
|
|
|
|
|
410
|
|
|
this.defaults = { |
|
411
|
|
|
// Strip slashes by default |
|
412
|
|
|
stripTrailingSlashes: true, |
|
413
|
|
|
|
|
414
|
|
|
// Default actions configuration |
|
415
|
|
|
actions: { |
|
416
|
|
|
'get': {method: 'GET'}, |
|
417
|
|
|
'save': {method: 'POST'}, |
|
418
|
|
|
'query': {method: 'GET', isArray: true}, |
|
419
|
|
|
'remove': {method: 'DELETE'}, |
|
420
|
|
|
'delete': {method: 'DELETE'} |
|
421
|
|
|
} |
|
422
|
|
|
}; |
|
423
|
|
|
|
|
424
|
|
|
this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { |
|
425
|
|
|
|
|
426
|
|
|
var noop = angular.noop, |
|
427
|
|
|
forEach = angular.forEach, |
|
428
|
|
|
extend = angular.extend, |
|
429
|
|
|
copy = angular.copy, |
|
430
|
|
|
isFunction = angular.isFunction; |
|
431
|
|
|
|
|
432
|
|
|
/** |
|
433
|
|
|
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow |
|
434
|
|
|
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set |
|
435
|
|
|
* (pchar) allowed in path segments: |
|
436
|
|
|
* segment = *pchar |
|
437
|
|
|
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" |
|
438
|
|
|
* pct-encoded = "%" HEXDIG HEXDIG |
|
439
|
|
|
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" |
|
440
|
|
|
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" |
|
441
|
|
|
* / "*" / "+" / "," / ";" / "=" |
|
442
|
|
|
*/ |
|
443
|
|
|
function encodeUriSegment(val) { |
|
444
|
|
|
return encodeUriQuery(val, true). |
|
445
|
|
|
replace(/%26/gi, '&'). |
|
446
|
|
|
replace(/%3D/gi, '='). |
|
447
|
|
|
replace(/%2B/gi, '+'); |
|
448
|
|
|
} |
|
449
|
|
|
|
|
450
|
|
|
|
|
451
|
|
|
/** |
|
452
|
|
|
* This method is intended for encoding *key* or *value* parts of query component. We need a |
|
453
|
|
|
* custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't |
|
454
|
|
|
* have to be encoded per http://tools.ietf.org/html/rfc3986: |
|
455
|
|
|
* query = *( pchar / "/" / "?" ) |
|
456
|
|
|
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" |
|
457
|
|
|
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" |
|
458
|
|
|
* pct-encoded = "%" HEXDIG HEXDIG |
|
459
|
|
|
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")" |
|
460
|
|
|
* / "*" / "+" / "," / ";" / "=" |
|
461
|
|
|
*/ |
|
462
|
|
|
function encodeUriQuery(val, pctEncodeSpaces) { |
|
463
|
|
|
return encodeURIComponent(val). |
|
464
|
|
|
replace(/%40/gi, '@'). |
|
465
|
|
|
replace(/%3A/gi, ':'). |
|
466
|
|
|
replace(/%24/g, '$'). |
|
467
|
|
|
replace(/%2C/gi, ','). |
|
468
|
|
|
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); |
|
469
|
|
|
} |
|
470
|
|
|
|
|
471
|
|
|
function Route(template, defaults) { |
|
472
|
|
|
this.template = template; |
|
473
|
|
|
this.defaults = extend({}, provider.defaults, defaults); |
|
474
|
|
|
this.urlParams = {}; |
|
475
|
|
|
} |
|
476
|
|
|
|
|
477
|
|
|
Route.prototype = { |
|
478
|
|
|
setUrlParams: function(config, params, actionUrl) { |
|
479
|
|
|
var self = this, |
|
480
|
|
|
url = actionUrl || self.template, |
|
481
|
|
|
val, |
|
482
|
|
|
encodedVal, |
|
483
|
|
|
protocolAndDomain = ''; |
|
484
|
|
|
|
|
485
|
|
|
var urlParams = self.urlParams = {}; |
|
486
|
|
|
forEach(url.split(/\W/), function(param) { |
|
487
|
|
|
if (param === 'hasOwnProperty') { |
|
488
|
|
|
throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); |
|
489
|
|
|
} |
|
490
|
|
|
if (!(new RegExp("^\\d+$").test(param)) && param && |
|
491
|
|
|
(new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { |
|
492
|
|
|
urlParams[param] = { |
|
493
|
|
|
isQueryParamValue: (new RegExp("\\?.*=:" + param + "(?:\\W|$)")).test(url) |
|
494
|
|
|
}; |
|
495
|
|
|
} |
|
496
|
|
|
}); |
|
497
|
|
|
url = url.replace(/\\:/g, ':'); |
|
498
|
|
|
url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) { |
|
499
|
|
|
protocolAndDomain = match; |
|
500
|
|
|
return ''; |
|
501
|
|
|
}); |
|
502
|
|
|
|
|
503
|
|
|
params = params || {}; |
|
504
|
|
|
forEach(self.urlParams, function(paramInfo, urlParam) { |
|
505
|
|
|
val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; |
|
506
|
|
|
if (angular.isDefined(val) && val !== null) { |
|
507
|
|
|
if (paramInfo.isQueryParamValue) { |
|
508
|
|
|
encodedVal = encodeUriQuery(val, true); |
|
509
|
|
|
} else { |
|
510
|
|
|
encodedVal = encodeUriSegment(val); |
|
511
|
|
|
} |
|
512
|
|
|
url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) { |
|
513
|
|
|
return encodedVal + p1; |
|
514
|
|
|
}); |
|
515
|
|
|
} else { |
|
516
|
|
|
url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, |
|
517
|
|
|
leadingSlashes, tail) { |
|
518
|
|
|
if (tail.charAt(0) == '/') { |
|
519
|
|
|
return tail; |
|
520
|
|
|
} else { |
|
|
|
|
|
|
521
|
|
|
return leadingSlashes + tail; |
|
522
|
|
|
} |
|
523
|
|
|
}); |
|
524
|
|
|
} |
|
525
|
|
|
}); |
|
526
|
|
|
|
|
527
|
|
|
// strip trailing slashes and set the url (unless this behavior is specifically disabled) |
|
528
|
|
|
if (self.defaults.stripTrailingSlashes) { |
|
529
|
|
|
url = url.replace(/\/+$/, '') || '/'; |
|
530
|
|
|
} |
|
531
|
|
|
|
|
532
|
|
|
// then replace collapse `/.` if found in the last URL path segment before the query |
|
533
|
|
|
// E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` |
|
534
|
|
|
url = url.replace(/\/\.(?=\w+($|\?))/, '.'); |
|
535
|
|
|
// replace escaped `/\.` with `/.` |
|
536
|
|
|
config.url = protocolAndDomain + url.replace(/\/\\\./, '/.'); |
|
537
|
|
|
|
|
538
|
|
|
|
|
539
|
|
|
// set params - delegate param encoding to $http |
|
540
|
|
|
forEach(params, function(value, key) { |
|
541
|
|
|
if (!self.urlParams[key]) { |
|
542
|
|
|
config.params = config.params || {}; |
|
543
|
|
|
config.params[key] = value; |
|
544
|
|
|
} |
|
545
|
|
|
}); |
|
546
|
|
|
} |
|
547
|
|
|
}; |
|
548
|
|
|
|
|
549
|
|
|
|
|
550
|
|
|
function resourceFactory(url, paramDefaults, actions, options) { |
|
551
|
|
|
var route = new Route(url, options); |
|
552
|
|
|
|
|
553
|
|
|
actions = extend({}, provider.defaults.actions, actions); |
|
554
|
|
|
|
|
555
|
|
|
function extractParams(data, actionParams) { |
|
556
|
|
|
var ids = {}; |
|
557
|
|
|
actionParams = extend({}, paramDefaults, actionParams); |
|
558
|
|
|
forEach(actionParams, function(value, key) { |
|
559
|
|
|
if (isFunction(value)) { value = value(); } |
|
560
|
|
|
ids[key] = value && value.charAt && value.charAt(0) == '@' ? |
|
561
|
|
|
lookupDottedPath(data, value.substr(1)) : value; |
|
562
|
|
|
}); |
|
563
|
|
|
return ids; |
|
564
|
|
|
} |
|
565
|
|
|
|
|
566
|
|
|
function defaultResponseInterceptor(response) { |
|
567
|
|
|
return response.resource; |
|
568
|
|
|
} |
|
569
|
|
|
|
|
570
|
|
|
function Resource(value) { |
|
571
|
|
|
shallowClearAndCopy(value || {}, this); |
|
572
|
|
|
} |
|
573
|
|
|
|
|
574
|
|
|
Resource.prototype.toJSON = function() { |
|
575
|
|
|
var data = extend({}, this); |
|
576
|
|
|
delete data.$promise; |
|
577
|
|
|
delete data.$resolved; |
|
578
|
|
|
return data; |
|
579
|
|
|
}; |
|
580
|
|
|
|
|
581
|
|
|
forEach(actions, function(action, name) { |
|
582
|
|
|
var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); |
|
583
|
|
|
var numericTimeout = action.timeout; |
|
584
|
|
|
var cancellable = angular.isDefined(action.cancellable) ? action.cancellable : |
|
585
|
|
|
(options && angular.isDefined(options.cancellable)) ? options.cancellable : |
|
586
|
|
|
provider.defaults.cancellable; |
|
587
|
|
|
|
|
588
|
|
|
if (numericTimeout && !angular.isNumber(numericTimeout)) { |
|
589
|
|
|
$log.debug('ngResource:\n' + |
|
590
|
|
|
' Only numeric values are allowed as `timeout`.\n' + |
|
591
|
|
|
' Promises are not supported in $resource, because the same value would ' + |
|
592
|
|
|
'be used for multiple requests. If you are looking for a way to cancel ' + |
|
593
|
|
|
'requests, you should use the `cancellable` option.'); |
|
594
|
|
|
delete action.timeout; |
|
595
|
|
|
numericTimeout = null; |
|
596
|
|
|
} |
|
597
|
|
|
|
|
598
|
|
|
Resource[name] = function(a1, a2, a3, a4) { |
|
599
|
|
|
var params = {}, data, success, error; |
|
600
|
|
|
|
|
601
|
|
|
/* jshint -W086 */ /* (purposefully fall through case statements) */ |
|
602
|
|
|
switch (arguments.length) { |
|
603
|
|
|
case 4: |
|
604
|
|
|
error = a4; |
|
605
|
|
|
success = a3; |
|
606
|
|
|
//fallthrough |
|
607
|
|
|
case 3: |
|
608
|
|
|
case 2: |
|
609
|
|
|
if (isFunction(a2)) { |
|
610
|
|
|
if (isFunction(a1)) { |
|
611
|
|
|
success = a1; |
|
612
|
|
|
error = a2; |
|
613
|
|
|
break; |
|
614
|
|
|
} |
|
615
|
|
|
|
|
616
|
|
|
success = a2; |
|
617
|
|
|
error = a3; |
|
|
|
|
|
|
618
|
|
|
//fallthrough |
|
619
|
|
|
} else { |
|
620
|
|
|
params = a1; |
|
621
|
|
|
data = a2; |
|
622
|
|
|
success = a3; |
|
623
|
|
|
break; |
|
624
|
|
|
} |
|
625
|
|
|
case 1: |
|
626
|
|
|
if (isFunction(a1)) success = a1; |
|
627
|
|
|
else if (hasBody) data = a1; |
|
628
|
|
|
else params = a1; |
|
629
|
|
|
break; |
|
630
|
|
|
case 0: break; |
|
631
|
|
|
default: |
|
632
|
|
|
throw $resourceMinErr('badargs', |
|
633
|
|
|
"Expected up to 4 arguments [params, data, success, error], got {0} arguments", |
|
634
|
|
|
arguments.length); |
|
635
|
|
|
} |
|
636
|
|
|
/* jshint +W086 */ /* (purposefully fall through case statements) */ |
|
637
|
|
|
|
|
638
|
|
|
var isInstanceCall = this instanceof Resource; |
|
639
|
|
|
var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); |
|
640
|
|
|
var httpConfig = {}; |
|
641
|
|
|
var responseInterceptor = action.interceptor && action.interceptor.response || |
|
642
|
|
|
defaultResponseInterceptor; |
|
643
|
|
|
var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || |
|
644
|
|
|
undefined; |
|
645
|
|
|
var timeoutDeferred; |
|
646
|
|
|
var numericTimeoutPromise; |
|
647
|
|
|
|
|
648
|
|
|
forEach(action, function(value, key) { |
|
649
|
|
|
switch (key) { |
|
650
|
|
|
default: |
|
|
|
|
|
|
651
|
|
|
httpConfig[key] = copy(value); |
|
652
|
|
|
break; |
|
653
|
|
|
case 'params': |
|
654
|
|
|
case 'isArray': |
|
655
|
|
|
case 'interceptor': |
|
656
|
|
|
case 'cancellable': |
|
657
|
|
|
break; |
|
658
|
|
|
} |
|
659
|
|
|
}); |
|
660
|
|
|
|
|
661
|
|
|
if (!isInstanceCall && cancellable) { |
|
662
|
|
|
timeoutDeferred = $q.defer(); |
|
663
|
|
|
httpConfig.timeout = timeoutDeferred.promise; |
|
664
|
|
|
|
|
665
|
|
|
if (numericTimeout) { |
|
666
|
|
|
numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); |
|
667
|
|
|
} |
|
668
|
|
|
} |
|
669
|
|
|
|
|
670
|
|
|
if (hasBody) httpConfig.data = data; |
|
671
|
|
|
route.setUrlParams(httpConfig, |
|
672
|
|
|
extend({}, extractParams(data, action.params || {}), params), |
|
673
|
|
|
action.url); |
|
674
|
|
|
|
|
675
|
|
|
var promise = $http(httpConfig).then(function(response) { |
|
676
|
|
|
var data = response.data; |
|
677
|
|
|
|
|
678
|
|
|
if (data) { |
|
679
|
|
|
// Need to convert action.isArray to boolean in case it is undefined |
|
680
|
|
|
// jshint -W018 |
|
681
|
|
|
if (angular.isArray(data) !== (!!action.isArray)) { |
|
682
|
|
|
throw $resourceMinErr('badcfg', |
|
683
|
|
|
'Error in resource configuration for action `{0}`. Expected response to ' + |
|
684
|
|
|
'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object', |
|
685
|
|
|
angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url); |
|
686
|
|
|
} |
|
687
|
|
|
// jshint +W018 |
|
688
|
|
|
if (action.isArray) { |
|
689
|
|
|
value.length = 0; |
|
690
|
|
|
forEach(data, function(item) { |
|
691
|
|
|
if (typeof item === "object") { |
|
692
|
|
|
value.push(new Resource(item)); |
|
693
|
|
|
} else { |
|
694
|
|
|
// Valid JSON values may be string literals, and these should not be converted |
|
695
|
|
|
// into objects. These items will not have access to the Resource prototype |
|
696
|
|
|
// methods, but unfortunately there |
|
697
|
|
|
value.push(item); |
|
698
|
|
|
} |
|
699
|
|
|
}); |
|
700
|
|
|
} else { |
|
701
|
|
|
var promise = value.$promise; // Save the promise |
|
702
|
|
|
shallowClearAndCopy(data, value); |
|
703
|
|
|
value.$promise = promise; // Restore the promise |
|
704
|
|
|
} |
|
705
|
|
|
} |
|
706
|
|
|
response.resource = value; |
|
707
|
|
|
|
|
708
|
|
|
return response; |
|
709
|
|
|
}, function(response) { |
|
710
|
|
|
(error || noop)(response); |
|
711
|
|
|
return $q.reject(response); |
|
712
|
|
|
}); |
|
713
|
|
|
|
|
714
|
|
|
promise.finally(function() { |
|
715
|
|
|
value.$resolved = true; |
|
716
|
|
|
if (!isInstanceCall && cancellable) { |
|
717
|
|
|
value.$cancelRequest = angular.noop; |
|
718
|
|
|
$timeout.cancel(numericTimeoutPromise); |
|
|
|
|
|
|
719
|
|
|
timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; |
|
720
|
|
|
} |
|
721
|
|
|
}); |
|
722
|
|
|
|
|
723
|
|
|
promise = promise.then( |
|
724
|
|
|
function(response) { |
|
725
|
|
|
var value = responseInterceptor(response); |
|
726
|
|
|
(success || noop)(value, response.headers); |
|
727
|
|
|
return value; |
|
728
|
|
|
}, |
|
729
|
|
|
responseErrorInterceptor); |
|
730
|
|
|
|
|
731
|
|
|
if (!isInstanceCall) { |
|
732
|
|
|
// we are creating instance / collection |
|
733
|
|
|
// - set the initial promise |
|
734
|
|
|
// - return the instance / collection |
|
735
|
|
|
value.$promise = promise; |
|
736
|
|
|
value.$resolved = false; |
|
737
|
|
|
if (cancellable) value.$cancelRequest = timeoutDeferred.resolve; |
|
738
|
|
|
|
|
739
|
|
|
return value; |
|
740
|
|
|
} |
|
741
|
|
|
|
|
742
|
|
|
// instance call |
|
743
|
|
|
return promise; |
|
744
|
|
|
}; |
|
745
|
|
|
|
|
746
|
|
|
|
|
747
|
|
|
Resource.prototype['$' + name] = function(params, success, error) { |
|
748
|
|
|
if (isFunction(params)) { |
|
749
|
|
|
error = success; success = params; params = {}; |
|
750
|
|
|
} |
|
751
|
|
|
var result = Resource[name].call(this, params, this, success, error); |
|
752
|
|
|
return result.$promise || result; |
|
753
|
|
|
}; |
|
754
|
|
|
}); |
|
755
|
|
|
|
|
756
|
|
|
Resource.bind = function(additionalParamDefaults) { |
|
757
|
|
|
return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); |
|
758
|
|
|
}; |
|
759
|
|
|
|
|
760
|
|
|
return Resource; |
|
761
|
|
|
} |
|
762
|
|
|
|
|
763
|
|
|
return resourceFactory; |
|
764
|
|
|
}]; |
|
765
|
|
|
}); |
|
766
|
|
|
|
|
767
|
|
|
|
|
768
|
|
|
})(window, window.angular); |
|
769
|
|
|
|